#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "mtm_wet3.h"
#include "parse.h"
#include "tournament.h"

/**
 * Open the input and output files
 * @param in a pointer to put pointer to input file in
 * @param out a pointer to put pointer to output file in
 * @param argc length of array argv
 * @param argv the command line arguments. (excluding the program name)
 * Note : *in and *out should be stdin and stdout, respectively
 * if there are not parameters about input/output, they will not change.
 * @return
 * true in case of success
 * false on error
 */
bool openFiles(FILE **in,FILE **out, int argc,char **argv) {
	if ((argc%2==1) || argc>4) {
		mtmPrintErrorMessage(stderr,MTM_INVALID_COMMAND_LINE_PARAMETERS);	
		return false;
	}
	for (int i=0;2*i+1<argc;i++) {
		FILE **toOpen=NULL; //pointless, and bad practice, but you force me.
		const char *mode=NULL;
		if (strcmp("-i",argv[2*i])==0) {
			if (*in!=stdin) {
				mtmPrintErrorMessage(stderr,
						MTM_INVALID_COMMAND_LINE_PARAMETERS);
				return false;
			}
			toOpen=in;
			mode="r";
		} else if (strcmp("-o",argv[2*i])==0) {
			if (*out!=stdout) {
				mtmPrintErrorMessage(stderr,
						MTM_INVALID_COMMAND_LINE_PARAMETERS);
				return false;
			}
			toOpen=out;
			mode="w";
		} else {
			mtmPrintErrorMessage(stderr,MTM_INVALID_COMMAND_LINE_PARAMETERS);	
			return false;
		}
		FILE *tmp=fopen(argv[2*i+1],mode);
		if (!tmp)  {
			mtmPrintErrorMessage(stderr,MTM_CANNOT_OPEN_FILE);	
			return false;
		}
		*toOpen=tmp;
	}
	return true;
}

/**
 * close the input and output files,
 * if different from stdin/stdout, respectively.
 * @param in the input file
 * @param out the output file
 */
void closeFiles(FILE *in, FILE *out) {
	if (in!=stdin) {
		fclose(in);
	}
	if (out!=stdout) {
		fclose(out);
	}
}

int main(int argc, char **argv) {
	FILE *in=stdin,*out=stdout;
	if (!openFiles(&in,&out,argc-1,argv+1)) {
		closeFiles(in,out);
		return 0;
	}

	Tournament tournament=tournamentCreate(NULL);
	if (!tournament) {
		closeFiles(in,out);
		return 0;
	}

	char buffer[MAX_LEN+1];
	while (fgets(buffer, MAX_LEN+1, in)) {
		if (!parse_input(buffer, out,tournament)) {
			break;
		}
	}

	tournamentDestroy(tournament);
	closeFiles(in,out);
	return 0;
}
